package org.zebra.file;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.zebra.file.excel.SimpleExcel;
import org.zebra.file.excel.core.ExportExcelHandlerMethodReturnValueHandler;
import org.zebra.file.excel.core.ImportExcelHandlerMethodArgumentResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanghongbin
 */
@AutoConfiguration
public class FileConfig {

    private SimpleExcel simpleExcel;

    public FileConfig(
            RequestMappingHandlerAdapter requestMappingHandlerAdapter,
            @Autowired(required = false) S3FileStorage s3FileStorage) {
        simpleExcel = new SimpleExcel(s3FileStorage);
        // 方法返回处理
        List<HandlerMethodReturnValueHandler> handlerMethodReturnValueHandlers = new ArrayList<>();
        // 放在第一个位
        handlerMethodReturnValueHandlers.add(new ExportExcelHandlerMethodReturnValueHandler(simpleExcel));
        handlerMethodReturnValueHandlers.addAll(requestMappingHandlerAdapter.getReturnValueHandlers());
        requestMappingHandlerAdapter.setReturnValueHandlers(handlerMethodReturnValueHandlers);
        // 方法参数解析映射
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        List<HandlerMethodArgumentResolver> resolverList = new ArrayList<>();
        // 放在第一个位
        resolverList.add(new ImportExcelHandlerMethodArgumentResolver(simpleExcel));
        resolverList.addAll(argumentResolvers);
        requestMappingHandlerAdapter.setArgumentResolvers(resolverList);
    }

    @Bean
    public SimpleExcel simpleExcel() {
        return simpleExcel;
    }
}
